﻿/// <reference path="jquery-2.0.2.js" />
/// <reference path="class.js" />
/// <reference path="persister.js" />
/// <reference path="ui.js" />

var controllers = (function () {
    var rootUrl = "https://leonardonews.apphb.com/api/";
    //var rootUrl = "http://localhost:4960/api/"

    var Controller = Class.create({
        init: function () {
            this.persister = persisters.get(rootUrl);
        },
        loadUI: function (selector) {
            if (this.persister.isUserLoggedIn()) {
                this.loadMainUI(selector);
            }
            else {
                this.loadLoginFormUI(selector);
                this.loadRegisterFormUI(selector)
            }
            this.attachUIEventHandlers(selector);
        },
        loadLoginFormUI: function (selector) {
            var loginForm = ui.loginForm();
            $(selector).html(loginForm);
        },
        loadRegisterFormUI: function (selector) {
            var registerF = ui.registerForm();
            $(selector).append(registerF);
        },
        loadMainUI: function (selector) {
            this.persister.articles.getAll(function (allArticles) {
                var mainUI = ui.mainUI(localStorage["username"], allArticles);
                $(selector).html(mainUI);
            }, function (error) {
                console.log(error);
            });
        },
        attachUIEventHandlers: function (selector) {
            var wrapper = $(selector);
            var self = this;

            wrapper.on("click", "#btn-login", function () {
                var user = {
                    username: $(selector + " #tb-login-username").val(),
                    password: $(selector + " #tb-login-password").val()
                }
                self.persister.user.login(
                    user,
                    function () {
                        self.loadMainUI(selector);
                    },
                    function (err) {
                        //wrapper.find("#error-messages").text("Error: " + err.responseJSON.Message);
                        wrapper.find("#error-messages").text("Invalid login!");
                        self.loadRegisterFormUI(selector);
                    });

                return false;
            });

            wrapper.on("click", "#btn-register", function () {
                var user = {
                    username: $(selector).find("#tb-register-username").val(),
                    password: $(selector + " #tb-register-password").val()
                }
                self.persister.user.register(
                    user,
                    function () {
                        self.loadMainUI(selector);
                    },
                    function (err) {
                        //wrapper.find("#error-messages").text(err.responseJSON.Message);
                        wrapper.find("#error-messages").text("Invalid register!");
                    });

                return false;
            });

            wrapper.on("click", "#btn-logout", function () {
                self.persister.user.logout(
                    function () {
                        self.loadLoginFormUI(selector);
                        self.loadRegisterFormUI(selector);
                    },
                    function (err) {
                        //alert("Error: " + err.responseJSON.Message);
                        alert("Error logging out!");
                    });

                return false;
            });

            wrapper.on("click", "#articles div", function (ev) {
                ev.stopPropagation();
                var id = $(this).attr("id");
                self.persister.articles.get(id, function (article) {
                    var articleView = ui.articleView(article);
                    wrapper.find("#article-container article").html(articleView);
                    wrapper.find("#article-container #article-img").attr("src", article.ImageUrl);
                    $('#vote-result').html(article.voteResult);
                    var comments = ui.comments(article);
                    var commentsContainer = wrapper.find("#comments-container");
                    $("#comments-container div").remove();
                    commentsContainer.append(comments);
                }, function (error) {
                    console.log(error);
                });

                return false;
            });
            wrapper.on("click", "#btn-create-article", function (ev) {
                ev.stopPropagation();
                var createArticleHtml = ui.createArticleHtml();
                wrapper.find("#article-container").html(createArticleHtml);

                return false;
            });

            wrapper.on("click", "#btn-post-article", function (ev) {
                var articleData = {
                    Title: wrapper.find("#tb-title").val(),
                    Text: wrapper.find("#ta-content").val(),
                    ImageUrl: wrapper.find("image-url").val()
                }
                this.persister.articles.create(articleData, function () {
                    //alert('Article created successfully!');
                    ui.pubNub();
                }, function (error) {
                    console.log(error);
                });

                return false;
            });
            wrapper.on("click", "#votes a", function () {
                var id = $(this).attr("id");
                var voteValue = $('#vote-result').val();
                var vote = { };

                if (id == "up") {
                    vote.State = 1;
                    voteValue++;
                }
                else if (id == "down") {
                    vote.State = -1;
                    voteValue--;
                }

                $('#vote-result').html(voteValue);
                return false;
            });
        },
    });

    return {
        get: function () {
            return new Controller();
        }
    }
}());